import java.util.Arrays;

/**
 * @author LKQ
 * @date 2022/2/21 16:58
 * @description
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] arr = {0,1,2,3,4,5,6,7,8};
        solution.sortByBits(arr);
    }
    public int[] sortByBits(int[] arr) {
        int n = arr.length;
        int[][] sort = new int[n][2];
        for (int i = 0 ; i < n; i++) {
            sort[i][0] = arr[i];
            sort[i][1] = cnt(arr[i]);
        }
        Arrays.sort(sort, (a, b) -> {
            if (a[1] != b[1]) {
                return a[1] - b[1];
            }else {
                return a[0] - b[0];
            }
        });
        int[] ans = new int[n];
        for (int i = 0; i < n; i++) {
            ans[i] = sort[i][0];
        }
        return ans;
    }
    public int cnt(int n ) {
        int sum = 0;
        while (n != 0) {
            if ((n & 1) == 1) {
                sum++;
            }
            n = n >> 1;
        }
        return sum;
    }
}
